import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useChat } from "./hooks/useChat";
import styles from "./chat.module.css";
import MarkdownIt from "markdown-it";
import hl from "highlight.js";
import useAuthStore from "@/store/auth";

export default function Chat() {
  const {
    messages,
    isTyping,
    loading,
    messagesEndRef,
    historyItems,
    isGeneratingTitle,
    sendMessage,
    getHistorys,
    stopGeneration,
    deleteMessage,
    copyMessage,
    loadHistory,
    setCurrentPromptId,
    setHistoryItems,
  } = useChat({
    apiEndpoint: "/v1/chat/completions",
    withContext: false,
    onError: (error) => {
      alert(`错误: ${error}`);
    },
    onSuccess: (message) => {
      console.log("消息发送成功:", message);
    },
    onAddHistory: (data) => {
      console.log("添加历史记录:", data);
    },
  });

  const md = new MarkdownIt({
    html: true,
    linkify: true,
    highlight: (str: string, lang: string) => {
      if (lang && hl.getLanguage(lang)) {
        return `<pre><code class="hljs">${
          hl.highlight(str, { language: lang }).value
        }</code></pre>`;
      }
      return `<pre><code>${str}</code></pre>`;
    },
  });

  const navigate = useNavigate();
  const [inputValue, setInputValue] = useState("");
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const { promptId } = useParams();
  /* 分页状态 */
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true); // 后端返回的是否还有下一页
  const [loadingHistory, setLoadingHistory] = useState(false); // 防止重复请求
  /* 滚动容器的 ref */
  const historyScrollRef = useRef<HTMLDivElement>(null);

  const [showSettingsMenu, setShowSettingsMenu] = useState(false);
  const settingsMenuRef = useRef<HTMLDivElement>(null);

  // 新增：用于记录每条消息的显示模式（html | code）
  const [messageViewModes, setMessageViewModes] = useState<
    Record<string, "html" | "code">
  >({});

  // 检测内容是否包含HTML标签
  const containsHtml = (content: string): boolean => {
    const htmlPattern =
      /<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>|<[a-z][a-z0-9]*\s*\/>/i;
    return htmlPattern.test(content);
  };

  // 切换查看模式
  const toggleViewMode = (messageId: string) => {
    setMessageViewModes((prev) => ({
      ...prev,
      [messageId]: prev[messageId] === "html" ? "code" : "html",
    }));
  };

  // 渲染消息内容
  const renderMessageContent = (message: any) => {
    const content = message.content as string;
    const hasHtml = containsHtml(content);
    const currentMode = messageViewModes[message.id] || "html";

    if (!hasHtml) {
      // 没有HTML，正常使用markdown渲染
      return (
        <div
          className="text-left text-sm md:text-base leading-relaxed"
          dangerouslySetInnerHTML={{
            __html: md.render(content),
          }}
        />
      );
    }

    // 有HTML内容
    if (currentMode === "html") {
      // 显示HTML实际效果
      return (
        <div
          className="text-left text-sm md:text-base leading-relaxed"
          dangerouslySetInnerHTML={{
            __html: content,
          }}
        />
      );
    } else {
      // 显示HTML代码
      return (
        <div className="text-left text-sm md:text-base leading-relaxed">
          <pre className="bg-gray-100 p-3 rounded overflow-x-auto">
            <code className="text-xs">{content}</code>
          </pre>
        </div>
      );
    }
  };

  const handleSendMessage = () => {
    if (inputValue.trim()) {
      sendMessage(inputValue, {
        promptId: promptId as string,
      });
      setInputValue("");
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleHistoryClick = (item: (typeof historyItems)[0]) => {
    loadHistory(item.id);
  };

  const handleDeleteClick = (id: string) => {
    if (window.confirm("确认删除该条记录？")) {
      deleteMessage(id);
    }
  };

  const handleBackToHome = () => {
    // 直接返回首页（更可靠）
    navigate("/home");
  };

  /* 加载更多历史记录 */
  const loadMoreHistory = async () => {
    if (loadingHistory || !hasMore || isGeneratingTitle) return; // 新增isGeneratingTitle判断

    setLoadingHistory(true);
    const nextPage = page + 1;

    const result = await getHistorys(promptId as string, nextPage, 10);

    if (result) {
      // 合并数据：追加到现有列表
      setHistoryItems((prev) => [...prev, ...result.rows]);
      setHasMore(result.hasMore);
      setPage(nextPage);
    }

    setLoadingHistory(false);
  };

  const handleLogout = () => {
    // 清除 token 或调用 store 的退出方法
    useAuthStore.getState().logout(); // 根据你的 store 实现调整

    // 跳转到登录页
    navigate("/login"); // 根据你的路由配置调整

    // 关闭菜单
    setShowSettingsMenu(false);
  };

  const toggleSettingsMenu = () => {
    setShowSettingsMenu((prev) => !prev);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        settingsMenuRef.current &&
        !settingsMenuRef.current.contains(event.target as Node)
      ) {
        setShowSettingsMenu(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    setCurrentPromptId(promptId as string);

    // 修改：处理返回的分页信息
    const initHistory = async () => {
      const result = await getHistorys(promptId as string, 1, 10);
      if (result) {
        setHistoryItems(result.rows);
        setHasMore(result.hasMore);
      }
    };

    initHistory();
  }, [promptId]);

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      textareaRef.current.style.height =
        Math.min(textareaRef.current.scrollHeight, 120) + "px";
    }
  }, [inputValue]);
  /* 监听滚动事件，当滚动到底部时触发加载更多 */
  useEffect(() => {
    const container = historyScrollRef.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;

      // 距离底部小于 50px 时触发加载
      if (scrollHeight - scrollTop - clientHeight < 50) {
        loadMoreHistory();
      }
    };

    container.addEventListener("scroll", handleScroll);
    return () => container.removeEventListener("scroll", handleScroll);
  }, [loadingHistory, hasMore, page]); // 依赖项

  return (
    <div className="h-screen bg-white flex flex-col">
      {/* 顶部导航 */}
      <header className="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
        <h1 className="text-xl md:text-2xl font-semibold text-gray-900">
          AI智能司法对话系统
        </h1>
        <div className="flex gap-3">
          <a
            href="#"
            className="px-4 py-2 text-sm text-gray-700 hover:text-blue-600 hover:bg-gray-50 rounded-lg transition-colors"
            onClick={handleBackToHome}
          >
            🏠 返回首页
          </a>
          {/* 修改：将设置按钮改为相对定位的容器 */}
          <div className="relative" ref={settingsMenuRef}>
            <button
              onClick={toggleSettingsMenu}
              className="hidden sm:inline-flex items-center gap-1 px-4 py-2 text-sm text-gray-700 hover:text-blue-600 hover:bg-gray-50 rounded-lg transition-colors"
            >
              ⚙️ 设置
              <svg
                className={`w-4 h-4 transition-transform ${
                  showSettingsMenu ? "rotate-180" : ""
                }`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M19 9l-7 7-7-7"
                />
              </svg>
            </button>

            {/* 下拉菜单 */}
            {showSettingsMenu && (
              <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50">
                <button
                  onClick={() => {
                    // 其他设置项逻辑
                    setShowSettingsMenu(false);
                  }}
                  className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2"
                >
                  ⚙️ 系统设置
                </button>

                <button
                  onClick={() => {
                    // 其他设置项逻辑
                    setShowSettingsMenu(false);
                  }}
                  className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2"
                >
                  👤 个人信息
                </button>

                <div className="border-t border-gray-200 my-1"></div>

                <button
                  onClick={handleLogout}
                  className="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2"
                >
                  🚪 退出登录
                </button>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* 主内容区域 */}
      <div className="flex-1 flex overflow-hidden">
        {/* 左侧历史记录 */}
        <aside
          ref={historyScrollRef}
          className={`${styles["custom-scrollbar"]} hidden lg:block w-72 xl:w-80 bg-gray-50 border-r border-gray-200 p-5 overflow-y-auto`}
        >
          <h3 className="text-base font-semibold text-gray-900 mb-4 pb-3 border-b border-gray-200">
            📚 历史对话
          </h3>
          <div className="space-y-2">
            {historyItems.map((item) => (
              <div
                key={item.id}
                onClick={() =>
                  item.id !== "slice-data" && handleHistoryClick(item)
                } // 占位数据不可点击
                className={`bg-white border rounded-lg p-3 transition-all ${
                  item.id === "slice-data"
                    ? "border-blue-300 cursor-default animate-pulse" // 占位数据特殊样式
                    : "border-gray-200 cursor-pointer hover:border-blue-400 hover:shadow-sm"
                }`}
              >
                <div className="text-sm font-medium text-gray-900 mb-1 overflow-hidden whitespace-nowrap text-ellipsis">
                  {item.id === "slice-data" && "✨ "}
                  {item.title}
                </div>
                <div className="text-xs text-gray-500">{item.createTime}</div>
              </div>
            ))}

            {/* 修改：加载提示不与标题生成冲突 */}
            {loadingHistory && !isGeneratingTitle && (
              <div className="text-center py-2 text-gray-500 text-xs">
                加载中...
              </div>
            )}

            {!hasMore && historyItems.length > 0 && (
              <div className="text-center py-2 text-gray-400 text-xs">
                没有更多记录了
              </div>
            )}
          </div>
        </aside>

        {/* 中间对话区域 */}
        <main className="flex-1 flex flex-col bg-gray-50">
          {/* 消息列表 */}
          <div className="flex-1 p-4 md:p-6 overflow-y-auto custom-scrollbar">
            {messages.length === 0 && (
              <div className="flex items-center justify-center h-full">
                <div className="text-center text-gray-500">
                  <div className="text-5xl mb-4">💬</div>
                  <p className="text-lg">开始您的法律咨询之旅</p>
                  <p className="text-sm mt-2">
                    输入您的问题，我将为您提供专业的法律建议
                  </p>
                </div>
              </div>
            )}

            {messages.map((message) => (
              <div
                key={message.id}
                className={`flex mb-4 group ${
                  message.type === "user" ? "justify-end" : "justify-start"
                }`}
              >
                {!(message.type === "user") && (
                  <div className="w-9 h-9 rounded-full bg-blue-500 flex items-center justify-center text-lg flex-shrink-0 mr-3">
                    🤖
                  </div>
                )}
                <div className="flex flex-col max-w-[70%] md:max-w-[60%]">
                  <div
                    className={`rounded-lg px-4 py-3 ${
                      message.type === "user"
                        ? "bg-blue-500 text-white"
                        : "bg-white border border-gray-200 text-gray-900"
                    }`}
                  >
                    {message.thinking ? (
                      <div className="flex items-center gap-2 text-gray-500">
                        <div className="flex gap-1">
                          <div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" />
                          <div
                            className="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
                            style={{ animationDelay: "0.1s" }}
                          />
                          <div
                            className="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
                            style={{ animationDelay: "0.2s" }}
                          />
                        </div>
                        <span className="text-sm">思考中...</span>
                      </div>
                    ) : (
                      renderMessageContent(message)
                    )}
                    <div
                      className={`text-xs mt-2 ${
                        message.type === "user"
                          ? "text-right text-blue-100"
                          : "text-left text-gray-500"
                      }`}
                    >
                      {message.createTime}
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  {!(message.type === "user") && !message.thinking && (
                    <div className="flex gap-2 mt-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      {containsHtml(message.content as string) && (
                        <button
                          onClick={() => toggleViewMode(message.id)}
                          className="text-xs text-gray-500 hover:text-blue-600 px-2 py-1 rounded hover:bg-gray-100"
                        >
                          {messageViewModes[message.id] === "code"
                            ? "🎨 查看效果"
                            : "📝 查看代码"}
                        </button>
                      )}
                      <button
                        onClick={() => copyMessage(message.content as string)}
                        className="text-xs text-gray-500 hover:text-blue-600 px-2 py-1 rounded hover:bg-gray-100"
                      >
                        📋 复制
                      </button>
                      <button
                        onClick={() => handleDeleteClick(message.id)}
                        className="text-xs text-gray-500 hover:text-red-600 px-2 py-1 rounded hover:bg-gray-100"
                      >
                        🗑️ 删除
                      </button>
                    </div>
                  )}
                </div>
                {message.type === "user" && (
                  <div className="w-9 h-9 rounded-full bg-green-500 flex items-center justify-center text-lg flex-shrink-0 ml-3">
                    👨‍💼
                  </div>
                )}
              </div>
            ))}

            {/* AI思考指示器 */}
            {isTyping && (
              <div className="flex mb-4">
                <div className="w-9 h-9 rounded-full bg-blue-500 flex items-center justify-center text-lg flex-shrink-0 mr-3">
                  🤖
                </div>
                <div className="bg-white border border-gray-200 rounded-lg px-4 py-3">
                  <div className="flex items-center gap-1.5">
                    <div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" />
                    <div
                      className="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
                      style={{ animationDelay: "0.1s" }}
                    />
                    <div
                      className="w-2 h-2 bg-blue-500 rounded-full animate-bounce"
                      style={{ animationDelay: "0.2s" }}
                    />
                  </div>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 */}
          <div className="bg-white border-t border-gray-200 p-4 md:p-6">
            <div className="flex gap-3 items-end">
              <textarea
                ref={textareaRef}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder="请输入您的问题或案件信息..."
                className={`${styles["custom-scrollbar"]} flex-1 bg-white border border-gray-300 rounded-lg px-4 py-3 text-gray-900 text-sm md:text-base resize-none min-h-[44px] max-h-[120px] focus:outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all placeholder:text-gray-400`}
                rows={1}
              />
              {loading ? (
                <button
                  onClick={stopGeneration}
                  className="px-5 py-3 bg-red-500 text-white rounded-lg font-medium whitespace-nowrap hover:bg-red-600 transition-colors"
                >
                  ⏹️ 停止
                </button>
              ) : (
                <button
                  onClick={handleSendMessage}
                  disabled={!inputValue.trim()}
                  className="px-5 py-3 bg-blue-500 text-white rounded-lg font-medium whitespace-nowrap hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-blue-500"
                >
                  发送
                </button>
              )}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}
